<!-- 用户管理 -->
<template>
  <!-- 用户列表 -->
  <div class="user-management">
    <div class="breadcrumb">
      <template v-if="showsUserListFlag">
        <span>{{ this.$route.meta.title }}</span>
      </template>
      <template v-else>
        <span style="color: #999999; cursor: pointer" @click="handleBackFn">{{ this.$route.meta.title }}</span>
        <span style="color: #999999">/</span>
        <span>
          <template v-if="operationType == 'new'">新增用户</template>
          <template v-else-if="operationType == 'edit'">编辑用户</template>
          <template v-else>查看用户</template>
        </span>
        <el-button class="float-right" type="text" icon="el-icon-back" @click="handleBackFn">返回</el-button>
      </template>
    </div>
    <div v-if="showsUserListFlag" class="layout-warpper user-management-main user-list-page">
      <div class="layout-header">
        <div class="layout-left">
          <el-button
            type="primary"
            icon="icon-xinzengsvg1"
            :disabled="JSON.stringify(USER_INIT_DATA) == '{}'"
            @click="addUser()"
          >
            新增用户
          </el-button>
          <!-- <el-button
            icon="icon-time"
            :disabled="JSON.stringify(USER_INIT_DATA) == '{}'"
            @click="timeSetting()"
          >
            时间设置
          </el-button> -->
        </div>
        <div class="layout-right">
          <el-input v-model.trim="keywords" class="ui-w310" placeholder="用户姓名" @keyup.native.enter="handleSearch()">
            <el-button slot="append" type="primary" icon="el-icon-search" @click="handleSearch()" />
          </el-input>
        </div>
      </div>
      <div class="layout-body">
        <el-table v-loading="tableLoading" :data="tableData" height="100%" isdrag>
          <el-table-column type="index" label="序号" width="50" align="center">
            <template slot-scope="scope">
              {{ (pageObj.currentPage - 1) * pageObj.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="userCode" label="人员编码" width="150" show-overflow-tooltip />
          <el-table-column
            prop="roleCode"
            label="用户角色"
            min-width="180"
            show-overflow-tooltip
            :formatter="roleCodeFormatter"
          />
          <el-table-column prop="userName" label="用户姓名" min-width="170" show-overflow-tooltip />
          <el-table-column
            prop="userIdCard"
            label="身份证号"
            width="225"
            show-overflow-tooltip
            :formatter="userIdCardFormatter"
          />
          <el-table-column prop="userTel" label="联系电话" width="130" show-overflow-tooltip />
          <el-table-column prop="loginName" label="登录名" width="180" show-overflow-tooltip />
          <el-table-column label="用户状态" width="140" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.userStatusEnum"
                active-value="ENABLE"
                inactive-value="DEACTIVATE"
                active-text="开启"
                inactive-text="关闭"
                active-color="#66bf16"
                active-text-color="#fff"
                inactive-color="#e5e5e5"
                inactive-text-color="#999"
                @change="userUpdateStatusFn(scope.row.userStatusEnum, scope.$index, scope.row.witnessUserId)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <!-- {{ userId }} -->
              <el-button
                :disabled="userId !== scope.row.parentId"
                type="text"
                @click="editOrViewUser(scope.row.witnessUserId, 'edit')"
              >
                编辑
              </el-button>
              <el-button type="text" @click="editOrViewUser(scope.row.witnessUserId, 'view')">查看</el-button>
              <el-button
                :disabled="userId !== scope.row.parentId"
                type="text"
                @click="deleteUser(scope.row.witnessUserId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="layout-footer ui-pt10">
        <pagination
          v-if="pageObj.total > pageObj.pageSizes[0]"
          :total="pageObj.total"
          :page.sync="pageObj.currentPage"
          :limit.sync="pageObj.pageSize"
          :page-sizes="pageObj.pageSizes"
          @pagination="userListFn()"
        />
      </div>
    </div>
    <!-- 用户信息组件 -->
    <UserInfo
      v-else
      class="user-management-main"
      :user-init-data="USER_INIT_DATA"
      :user-status-radios="USER_INIT_DATA.userStatus"
      :user-role-checkboxs="USER_INIT_DATA.userRoleList"
      :role-list="USER_INIT_DATA.roleList"
      :industry-type-options="USER_INIT_DATA.industryTypeAndIndustry"
      :industry-type-and-tender-mode-arr="USER_INIT_DATA.industryTypeAndIndustry"
      :witness-link="USER_INIT_DATA.witnessLink"
      :tender-modes="USER_INIT_DATA.tenderModes"
      :industry-all="USER_INIT_DATA.industryAll"
      :industry-types="USER_INIT_DATA.industryTypes"
      :operation-type="operationType"
      :witness-user-id="witnessUserId"
      @close="closeUserInfoPage"
    />
  </div>
</template>
<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  import UserInfo from "../components/UserManagement/UserInfo.vue";
  import { moduleInit, userList, userUpdateStatus, userDelete } from "../../../api/api";
  export default {
    // 引入组件
    components: {
      UserInfo
    },
    props: {},
    data() {
      // 这里存放数据
      return {
        showsUserListFlag: true, // 展示用户列表的标志
        USER_INIT_DATA: {}, // 接口返回的，字典数据信息
        userRoleObj: {}, // 用户角色key-value映射值
        userId: sessionStorage.getItem("userId"),
        keywords: "",
        tableData: [],
        tableLoading: true,
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        operationType: "new", // 操作类型，new(新增)，edit(编辑)，view(查看)
        witnessUserId: "" // 用户编辑和查看的数据id
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.userId = sessionStorage.getItem("userId");
      this.moduleInitFn();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    // 生命周期 - 销毁之前
    beforeDestroy() {},
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      console.log("activated");
      // this.userId = sessionStorage.getItem("userId");
      // this.moduleInitFn();
    },
    // 方法集合
    methods: {
      // 返回
      handleBackFn() {
        this.showsUserListFlag = true;
        // this.userListFn();
        this.moduleInitFn();
      },
      // 获取初始化数据
      async moduleInitFn() {
        try {
          const res = await moduleInit({ moduleName: "USER" });
          if (res.success) {
            this.USER_INIT_DATA = res.data;
            // 获取用户角色key-value映射值
            for (let i = 0; i < res.data.roleList.length; i++) {
              this.userRoleObj[res.data.roleList[i].value] = res.data.roleList[i].label;
            }
            this.handleSearch();
          } else {
            this.tableLoading = false;
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          this.tableLoading = false;
          console.error(error);
        }
      },
      handleSearch() {
        this.pageObj.total = 0;
        this.pageObj.currentPage = 1;
        this.userListFn();
      },
      async userListFn() {
        try {
          this.tableLoading = true;
          this.tableData = [];
          const params = {
            userName: this.keywords, // 用户姓名
            currentPage: this.pageObj.currentPage, // 当前页数
            pageSize: this.pageObj.pageSize // 每页条数
          };
          const res = await userList(params);
          this.tableLoading = false;
          if (res.success) {
            this.tableData = res.data.data;
            this.pageObj.total = res.data.pageBean.count;
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          this.tableLoading = false;
          console.error(error);
        }
      },
      // 格式化用户角色
      roleCodeFormatter(row, column, cellValue) {
        if (cellValue) {
          const oriArr = cellValue.split(",");
          const newArr = [];
          for (let i = 0; i < oriArr.length; i++) {
            newArr.push(this.userRoleObj[oriArr[i]]);
          }
          return newArr.join("、");
        }
        return "";
      },
      // 格式化身份证号
      userIdCardFormatter(row, column, cellValue) {
        if (cellValue) {
          return cellValue.replace(/\d/g, (d, i) => {
            if (i > 3 && i < cellValue.length - 4) {
              return "*";
            }
            return d;
          });
        }
        return "";
      },
      // 关闭用户信息组件
      closeUserInfoPage() {
        this.showsUserListFlag = true;
        this.userListFn();
      },
      // 新增用户
      addUser() {
        this.operationType = "new";
        this.showsUserListFlag = false;
      },
      // 编辑、查看用户
      editOrViewUser(witnessUserId, type) {
        this.operationType = type;
        this.witnessUserId = witnessUserId;
        this.showsUserListFlag = false;
      },
      // 删除
      deleteUser(witnessUserId) {
        this.$confirm("此操作将永久删除该用户，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.userDeleteFn(witnessUserId);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
              single: true
            });
          });
      },
      // 修改用户状态
      async userUpdateStatusFn(userStatusEnum, index, witnessUserId) {
        // 在接口未成功修改之前，先保持原来的值不变
        if (userStatusEnum === "ENABLE") {
          this.$set(this.tableData[index], "userStatusEnum", "DEACTIVATE");
        } else {
          this.$set(this.tableData[index], "userStatusEnum", "ENABLE");
        }
        try {
          this.tableLoading = true;
          const params = {
            witnessUserId: witnessUserId,
            userStatus: userStatusEnum
          };
          const res = await userUpdateStatus(params);
          if (res.success) {
            this.$message({
              type: "success",
              message: "修改成功",
              single: true
            });
            this.userListFn();
          } else {
            this.tableLoading = false;
            this.$message({
              type: "error",
              message: res.message || "修改失败",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.tableLoading = false;
        }
      },
      // 删除用户
      async userDeleteFn(witnessUserId) {
        try {
          this.tableLoading = true;
          const res = await userDelete({ witnessUserId });
          if (res.success) {
            this.$message({
              type: "success",
              message: "删除成功",
              single: true
            });
            this.handleSearch();
          } else {
            this.tableLoading = false;
            this.$message({
              type: "error",
              message: res.message || "删除失败",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.tableLoading = false;
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .breadcrumb {
    padding: 5px 15px;
    background: #fff;
    // color: #333;
    font-weight: bold;
    font-size: 14px;
    line-height: 34px;
  }
  .user-management {
    width: 100%;
    height: 100%;
    &-main {
      width: 100%;
      height: 100%;
      display: flex;
      flex-flow: column;
      box-sizing: border-box;
      // padding: 10px;
      background-color: #fff;
      border: 10px solid #eee;
      overflow: auto;
    }
    .user-list-page {
      padding: 10px;
    }
  }
</style>
<style lang="scss"></style>
